<script setup lang="tsx">
import { Form, FormSchema } from '@/components/Form'
import { useForm } from '@/hooks/web/useForm'
import { PropType, reactive, watch } from 'vue'
import { useValidator } from '@/hooks/web/useValidator'
import { EmergencyEventType } from '@/api/Emergency/type'
const { required } = useValidator()

const props = defineProps({
  currentRow: {
    type: Object as PropType<Nullable<EmergencyEventType>>,
    default: () => null
  }
})

const rules = reactive({
  areaType: [required()],
  areaName: [required()],
  orderNum: [required()]
})
const formSchema = reactive<FormSchema[]>([
  {
    field: 'areaName',
    label: '名称',
    component: 'Input',
    colProps: {
      span: 20
    }
  },
  {
    field: 'areaType',
    label: '片区类型',
    component: 'RadioGroup',
    componentProps: {
      options: [
        {
          label: '用户',
          value: 'user'
        },
        {
          label: '工业',
          value: 'industry'
        },
        {
          label: '商业',
          value: 'business'
        }
      ]
    },
    colProps: {
      span: 20
    }
  },
  {
    field: 'orderNum',
    label: '排序',
    component: 'InputNumber',
    colProps: {
      span: 20
    }
  }
])
const { formRegister, formMethods } = useForm()
const { setValues, getFormData, getElFormExpose } = formMethods

const submit = async () => {
  const elForm = await getElFormExpose()
  const valid = await elForm?.validate().catch((err) => {
    console.log(err)
  })
  if (valid) {
    const formData = await getFormData()
    return formData
  }
}

watch(
  () => props.currentRow,
  (currentRow) => {
    if (!currentRow) return
    setValues(currentRow)
  },
  {
    deep: true,
    immediate: true
  }
)

defineExpose({
  submit
})
</script>

<template>
  <Form :rules="rules" @register="formRegister" :schema="formSchema" />
</template>

